var wuItemParams = "";

var QuestionSet = {
    /**
     * This method is used to remove a question from current question set. It just remove the html segment.
     * Called by the button with id "rqBtn".
     */
    removeQuestion : function () {
        /*
         * The commonRemove is used under the easiest condition. This method only remove the html
         * element of the question node will be deleted and update the attributs for the nodes will
         * be affected by this deletion action.
         */
        var commonRemove = function () {
            getNodeBySequence(currentNode.sequence).remove();
            var nextSibling = currentNode.downSibling;
            while (nextSibling != null) {
                var newSeq = nextSibling.substring(0, nextSibling.lastIndexOf(".") + 1) +
                             eval(nextSibling.substring(nextSibling.lastIndexOf(".") + 1, nextSibling.length) + "-1");
                updateSequence(nextSibling, newSeq);
                nextSibling = getNodeInfo(nextSibling).downSibling;
            }
        }

        // Remove these questions from a question set.
        var removeQuestionFromSet = function () {
            if (currentNode.child != null) {
                if (currentNode.upSibling != null) {
                    // If the node has an upsibling, then its children will belong to its upsibling.
                    var child = currentNode.child;
                    while (child != null) {
                        updateSequence(child, currentNode.upSibling +
                                              child.substring(currentNode.sequence.length, child.length));
                        child = getNodeInfo(child).downSibling;
                    }
                    // Remove this node.
                    commonRemove();
                } else {
                    var currentIndex = currentNode.sequence;
                    changeCurrentNode(currentNode.child);
                    out();
                    changeCurrentNode(currentIndex);
                    commonRemove();
                }
            } else {
                commonRemove();
            }

            // Display message.
            $("div.error h3").html("Selected Question has been removed from this Page.");
        }

        removeQuestionFromSet();

        //Dialogs.inactiveBtn($("#editQuestionBtn"), lightColorFlag);
        //Dialogs.inactiveBtn($("#viewQuestionBtn"), lightColorFlag);
        //Dialogs.inactiveBtn($("#rqBtn"), lightColorFlag);
        //Dialogs.inactiveBtn($("#moveUpBtn"), lightColorFlag);
        //Dialogs.inactiveBtn($("#moveDownBtn"), lightColorFlag);
        //Dialogs.inactiveBtn($("#moveOutBtn"), lightColorFlag);
        //Dialogs.inactiveBtn($("#moveInBtn"), lightColorFlag);
        
        $("#moveUpBtn").attr("disabled", true);
        $("#moveDownBtn").attr("disabled", true);
        $("#moveOutBtn").attr("disabled", true);
        $("#moveInBtn").attr("disabled", true);
        itemParams = "";
    },

    includeQuestion : function () {
        var getMaxSeq = function() {
            var maxSeq = $("table[parent='.']:last").attr(SEQUENCE_ATTR);

            if (maxSeq == undefined)
                maxSeq = 0;

            return maxSeq;
        }
		var THIS = this;
        if (qId != null) {
            if (qStatus != 'retired') {
                if ($("[questionid=" + qId + "]").length > 0 || THIS.checkHave()) {
                    $("div.message h3").html("<font color='red'>A question cannot be included twice.</font>");
                } else {
                    $.get("includequestion.html", {
                        "qId" : qId,
                        "maxSequence" : getMaxSeq()
                    }, function(data) {                    	
                        $("#questionList").append(data);
                    });
					THIS.checkHaveStyle();
                    $("div.message h3").html("Question successfully included.");
                    var plural = "";
                    if ($("#questionList table").size() > 0) plural = "s";
                    $("#questionListMessage").html("This Page contains the following " + ($("#questionList table").size() + 1) + " Question" + plural + ":");
                    
                }
            } else {
                $("div.message h3").html("<font color='red'>Retired question cannot be included</font>");
            }
        } else {
            alert("Please select a Question before choosing Include Question");
        }
    },
    /**
      * Add By he
      */
	checkHaveStyle : function(){
		var includeObjs = $("div.question").children();
		var includeObjString = ",";
		includeObjs.each(function(){
			var thisId = $(this).attr("questionid");
			includeObjString += thisId+",";		
		});
		var includeList=includeObjString.split(",");	
		var allObjs = $("#qresults").children();
		allObjs.each(function(){
			var ThisID = $(this).attr("id");		
			if (includeList.indexOf(ThisID)>0){
				$(this).addClass("visited");
			}		
		});
	},
	checkHave : function(){
	    var includeObjs = $("div.question").children();
		var includeObjString = ",";
		includeObjs.each(function(){
			var thisId = $(this).attr("questionid");					
			includeObjString += thisId+",";		
		});	
		var includeList=includeObjString.split(",");	
		var checkFlag = false; 
		for (i=0;i<includeList.length;i++){
			if (includeList[i]==qId){
				checkFlag = true;
			}
		} 
		return checkFlag; 
	},
    /**
     * The method is used by editQuestions.jsp and viewQuestions.jsp.
     */
    subItemClick : function (item, params) {
        var btns = document.getElementsByName("qbtn");

        if ($(item).attr("class").indexOf("active") == -1) {
            // Remove the active class for other items. (editQuestions.jsp)
            $("div.question table").removeClass("active");
            // Remove the active class for other items. (whereUsed.jsp)
            $("#dataList div").removeClass("active");

            $(item).addClass("active");

            itemParams = params;
            for (i = 0; i < btns.length; i++) {
                var btn = btns[i];

                // Enable the button.
                $(btn).removeAttr("disabled");

                var imgSrc = $(btn).attr("src");
                var newSrc = imgSrc.replace(lightColorFlag, '.');
                $(btn).attr("src", newSrc);
            }
        } else {
            $(item).removeClass("active");

            itemParams = "";

            for (i = 0; i < btns.length; i++) {
                var btn = btns[i];

                $(btn).removeClass("btn");

                // Disable the button.
                $(btn).attr("disabled", true);

                var imgSrc = $(btn).attr("src");
                var newSrc = imgSrc.replace(".", lightColorFlag);
                $(btn).attr("src", newSrc);
            }
        }
    },

    /**
     * This method is used for getting the info of the "Questions" included in a "Page".
     */
    getSequences : function () {
        var gatherQuestionsInfo = function () {
            var dataList = new Array();
            $("#questionList table").each(function() {
                var qData = {};
                qData.qisId = $(this).attr("qisId");
                qData.questionId = $(this).attr("questionId");
                qData.sequence = $(this).attr(SEQUENCE_ATTR);
                dataList.push(qData);
            });

            return dataList;
        }
        var dataList = gatherQuestionsInfo();

        return JSON.stringify(dataList);
        //QuestionSetService.saveSequences(qsId, dataList);

        // Display the message.
        //$("div.error h3").html("Page has been updated");
    },

    /**
     * The method is used for doing necessary works before submit the 'Create', 'Edit', 'New Version', 'Copy' form.
     * Works: Gather the info of the 'Questions' included in a 'Page'; Store the info of the 'Questions';
     */
    actionBeforePost : function () {
        var seqJSON = this.getSequences();
        $("#questionsData").val(seqJSON);
        $("#questionsBak").val($("#questionList").html());
        $("#questionListMsgBak").val($("#questionListMessage").html());
        Dialogs.saveTargetValue();
    },

    itemClick : function (item, params) {
        var lightColorFlag = "_light.";
        $("div.data_tbody div").removeClass("active");
        var visitedCss = $(item).attr("class");
	    if (visitedCss.indexOf("visited")>0){
	    	$(item).removeClass("visited"); 
	    }
        $(item).addClass("active");
        itemParams = params;

        Dialogs.activeBtn($("#editBtn"), lightColorFlag);
        Dialogs.activeBtn($("#deleteBtn"), lightColorFlag);
        Dialogs.activeBtn($("#nvBtn"), lightColorFlag);
        Dialogs.activeBtn($("#retireBtn"), lightColorFlag);

        if ($(item).attr("status") == 'retired' || $(item).attr("availability") == 'locked') {
            Dialogs.inactiveBtn($("#editBtn"), lightColorFlag);
        }

        if ($(item).attr("status") == 'retired' || $(item).attr("availability") == 'locked' || $(item).attr("involvedNum") > 0) {
            Dialogs.inactiveBtn($("#deleteBtn"), lightColorFlag);
        }

        if ($(item).attr("status") == 'retired') {
            Dialogs.inactiveBtn($("#nvBtn"), lightColorFlag);
            Dialogs.inactiveBtn($("#retireBtn"), lightColorFlag);
        }
        if (visitedCss.indexOf("visited")>0){
	    	$(item).addClass("visited"); 
	    }
    },

    /**
     * The method is used by editQuestions.jsp and viewQuestions.jsp.
     */
    wuItemClick : function (item, params, btnGroupName) {
        var btns = document.getElementsByName(btnGroupName);

        if ($(item).attr("class").indexOf("active") == -1) {
            // Remove the active class for other items. (whereUsed.jsp)
            $("#dataList div").removeClass("active");

            // The clicked item is set as "Active".
            $(item).addClass("active");

            wuItemParams = params;

            for (var i = 0; i < btns.length; i++) {
                var btn = btns[i];

                // Enable the button.
                $(btn).removeAttr("disabled");

                var imgSrc = $(btn).attr("src");
                var newSrc = imgSrc.replace(lightColorFlag, '.');
                $(btn).attr("src", newSrc);
            }

            // This block of code is used by whereUsed.jsp in 'Page' Module.
            if ($(item).attr("pstatus") != 'inprocess') {
                this.inactiveBtn($("#editDialogBtn"), lightColorFlag);
            }
        } else {
            $(item).removeClass("active");

            wuItemParams = "";

            for (var i = 0; i < btns.length; i++) {
                var btn = btns[i];

                $(btn).removeClass("btn");

                // Disable the button.
                $(btn).attr("disabled", true);

                var imgSrc = $(btn).attr("src");
                if (imgSrc.indexOf(lightColorFlag) == -1)
                    imgSrc = imgSrc.replace(".", lightColorFlag);
                $(btn).attr("src", imgSrc);
            }
        }
    },

    wuClickAction : function(action, isBlank) {
        if (wuItemParams == "") {
            alert("Please select an item.");
        } else if (!isBlank) {
            var currentUrl = "&from=" + escape(window.location.href);
            wuItemParams += currentUrl;
            window.location.href = action + ".html?" + wuItemParams;
        } else {
            window.open(action + ".html?" + wuItemParams);
        }
    },

    initWuActionButtons : function (btnGroupName) {
        var btns = document.getElementsByName(btnGroupName);

        for (var i = 0; i < btns.length; i++) {
            var btn = btns[i];
            Dialogs.inactiveBtn($(btn), lightColorFlag);
        }
    }
}